<style scoped lang="scss">
</style>
<template>
    <view class="send-verify">
		<button @click="sendVerify" type="primary" size="mini">{{ label }}</button>
    </view>
</template>
<script>
export default {
    name: 'xySendVerify',
    props: {
        account: {
			type: String,
			default: ''
		},
        title: {
			type: String,
			default: ''
		},
		url: {
			type: String,
			default: '/v1/sms/verify/send'
		},
		type: {
			type: String,
			default: '手机号'
		},
		time: {
			type: Number,
			default: 30
		}
    },
    data() {
        return {
            label: '发送验证码',
            timeLeft: 0
        }
    },
    created: function () {
    },
    methods: {
        async sendVerify () {
			if (this.timeLeft > 0) {
				return;
			}
            if (!this.account) {
				this.util.showToast({
					title: '请输入' + this.type,
					icon: 'loading',
					duration: 1000
				});
                return false;
            }
			this.timeLeft = this.time;
            this.label = '剩余' + this.timeLeft + 's';
            var timer = setInterval(()=>{
                this.timeLeft--
                if (this.timeLeft <= 0) {
                    this.label = '发送验证码';
                    this.timeLeft = 0;
                    clearInterval(timer);
                } else {
                    this.label = '剩余' + this.timeLeft + 's'
                }
            }, 1000);
			let data = {};
			if (this.type == '手机号') {
				data = {
					mobile: this.account,
					title: this.title
				};
			} else {
				data= {
					email: this.account,
					title: this.title
				};
			}
            let res = await this.util.request({
                url: this.url,
                data: data,
                method: 'post',
            });
            if (res.code == '200') {
				this.util.showToast({
					title: res.msg,
					icon: 'success',
					duration: 1000
				});
                // 事件
                this.$emit('verifysuccess', res.data)
            } else {
				this.util.showToast({
					title: res.msg,
					icon: 'loading',
					duration: 2000
				});
            }
        }
    }
}
</script>
